package cn.blossoming.test

import cn.blossoming.service.base.utils.OssUtils
import cn.blossoming.service.user.UserService
import cn.blossoming.service.video.VideoService
import com.qiniu.common.QiniuException
import com.qiniu.common.Zone
import com.qiniu.storage.BucketManager
import com.qiniu.storage.Configuration
import com.qiniu.storage.UploadManager
import com.qiniu.storage.model.FileInfo
import org.apache.commons.io.FileUtils
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import java.net.URL
import java.nio.file.Paths


class VideoServiceTest : BaseTest() {
    val uriPreFix = "http://ouptwd2d5.bkt.clouddn.com/"
    val basUrl = "http://up.qiniu.com/"
    val bucket = "blosson"


    @Autowired lateinit var videoService: VideoService
    @Autowired lateinit var userService: UserService

    val um: UploadManager
    val bm: BucketManager
    val keys: List<String>

    init {
        val configuration = Configuration(Zone.zone0())
        um = UploadManager(configuration)
        bm = BucketManager(OssUtils.getAuth(), configuration)
        val listFiles = bm.listFiles(bucket, null, null, 1000, null)
        keys = listFiles.items.map(FileInfo::key)
    }

    @Test
    fun update() {
        val all = userService.findAll()
        all.stream().forEach {
            if (!it.avatar.contains("http://ouptwd2d5.bkt.clouddn.com")) {
                it.avatar = upload(it.avatar)
                userService.save(it)
            }
        }


    }

    fun upload(url: String): String {
        var endIndex = url.lastIndexOf("?")
        if (endIndex == -1)
            endIndex = url.length
        val key = url.substring(url.indexOf("/", 10) + 1, endIndex)
        val file = Paths.get("/tmp/" + key).toFile()
        try {
            FileUtils.copyURLToFile(URL(url), file)
            val auth = OssUtils.getAuth()
            val token = auth.uploadToken(bucket)
            try {
                um.put(file, key, token)
            } catch (ex: QiniuException) {
                println(ex.code())
                println(ex.response.error)
            }
        } catch (e: Exception) {
            println(e)
        } finally {
            file.delete()
        }

        return uriPreFix + key

    }

}